package com.mintuo.litecomposite.common.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import com.mintuo.litecomposite.LitecompositeApplication;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.boot.SpringApplication;

import java.nio.charset.Charset;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.spec.ECGenParameterSpec;
import java.util.HashMap;
import java.util.Map;

public class SMUtil {

    public Map<String, String> generateSm2KeyPair() {
        Map<String, String> keypairMap = new HashMap<>();

        try {
            SM2 sm2 = SmUtil.sm2();
            // 获取密钥对
            String privateKey = Base64.encode(sm2.getPrivateKey().getEncoded());
            String publicKey = Base64.encode(sm2.getPublicKey().getEncoded());

            keypairMap.put("privateKey",privateKey);
            keypairMap.put("publicKey",publicKey);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return keypairMap;
    }

    public static void main(String[] args) {

        //SMUtil util = new SMUtil();
        //Map<String,String> kpMap = util.generateSm2KeyPair();

        String privatekeystr = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgRIaDJdmaYVTBOpvor66YQ0JbRtP/HCXl60X3gKoesyCgCgYIKoEcz1UBgi2hRANCAAQXFU0WMLqEMZXW0KDXuSAm/P6nw5BMQoriRxMwInK1OAewpbZZD1YnvQtVt0pLD+w7USQ4e0ZP2rD5CoKTcOG3";
        String publickeyStr = "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEFxVNFjC6hDGV1tCg17kgJvz+p8OQTEKK4kcTMCJytTgHsKW2WQ9WJ70LVbdKSw/sO1EkOHtGT9qw+QqCk3Dhtw==";
        byte[] privatekey = Base64.decode(privatekeystr);
        byte[] publickey = Base64.decode(publickeyStr);
        SM2 sm2 = new SM2(privatekey,publickey);
//        byte[] privatekey = sm2.getPrivateKey().getEncoded();
//        String privatekeystr = Base64.encode(privatekey);
//        byte[] publickey = sm2.getPublicKey().getEncoded();
//        String publickeyStr = Base64.encode(publickey);


        String ss = "Founder@123!";

        byte[] bb = StrUtil.bytes(ss,"UTF-8");
        byte[] encdata = sm2.encrypt(bb);

        String encStr = StrUtil.str(encdata,"UTF-8");

        byte[] decdata = sm2.decrypt(encdata,KeyType.PrivateKey);

        String decStr = StrUtil.str(decdata,"UTF-8");

        System.out.println("ok");
    }

}
